/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Telas;

import Beans.BeanAgendamento;
import Beans.BeanPessoa;
import Beans.BeanProntuario;
import CRUD.CRUDAgendamento;
import CRUD.CRUDProntuario;
import ClassesExtras.JTableScroll;
import ClassesExtras.TextAreaMaiuscula;
import java.awt.Color;
import java.awt.Component;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Marcos
 */
public class Jp_CadastroAgendamentoMedico extends javax.swing.JPanel {

    DefaultTableModel TMAgendamento = new DefaultTableModel(null, new String[]{"Agendamento", "Agendado_Para:",
        "Horário", "Status", "Médico", "Paciente", "Telefone", "Nascimento",
        "Idade", "Sexo", "Cidade", "Endereço", "Observação"}) {// Faz a sobreposição de método e permite tbm a instancia de classe abstrata, quando implementado seus métodos
        @Override
        public boolean isCellEditable(int row, int column) {
            return false; //Não deixar editar uma linha da JTable
//            return super.isCellEditable(row, column);
        }
    };
    DefaultTableModel TMProntuario = new DefaultTableModel(null, new String[]{"Data", "Prontuário"}) {// Faz a sobreposição de método e permite tbm a instancia de classe abstrata, quando implementado seus métodos
        @Override
        public boolean isCellEditable(int row, int column) {
            return false; //Não deixar editar uma linha da JTable
//            return super.isCellEditable(row, column);
        }
    };
    private DefaultTableModel tabela;
    Object[] btSimNao = {"Sim", "Não"};
    List<BeanPessoa> ListaPessoa;
    List<BeanAgendamento> ListaAgendamento;
    List<BeanProntuario> ListaProntuario;
    String data_atual;
    Integer cod_prontuario;

    /**
     * Creates new form Jp_CadastroAgendamentoMedico
     */
    public Jp_CadastroAgendamentoMedico() {
        initComponents();
        jTableHistoricoProntuario.setRowHeight(100);  //aumentar a altura da linha           
        AlinhaColunaJTable();
        jTableAgendamento.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Selecionar somente uma linha da JTable
        jTabbedPaneAgendamentoMedico.setEnabledAt(1, false);
        try {
            listaagendamento();
        } catch (Exception ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
        jTextAreaProntuario.setLineWrap(true);

        Date data = new Date(System.currentTimeMillis());
        SimpleDateFormat formatarDate = new SimpleDateFormat("dd/MM/yyyy");
        data_atual = formatarDate.format(data);
        run();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPaneAgendamentoMedico = new javax.swing.JTabbedPane();
        jPanelAgendamentoMedico = new javax.swing.JPanel();
        jLabelCamposObrigatorios = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableAgendamento = new javax.swing.JTable();
        jButtonAlterar = new javax.swing.JButton();
        jButtonIncluir = new javax.swing.JButton();
        jButtonNovo = new javax.swing.JButton();
        jComboBoxStatus = new javax.swing.JComboBox();
        jLabelStatus = new javax.swing.JLabel();
        jLabelAgendamento = new javax.swing.JLabel();
        jTextFieldAgendamento = new javax.swing.JTextField();
        jLabelPlanoSaude = new javax.swing.JLabel();
        jLabelDenPlanoSaude = new javax.swing.JLabel();
        jCalendarAgendamento = new com.toedter.calendar.JCalendar();
        jPanel1 = new javax.swing.JPanel();
        jLabelNomPaciente = new javax.swing.JLabel();
        jLabelCodPaciente = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextAreaProntuario = new TextAreaMaiuscula();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTableHistoricoProntuario = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jLabelPlanoSaudeProntuario = new javax.swing.JLabel();
        jLabelDenPlanoSaudeProntuario = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabelCamposObrigatorios.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabelCamposObrigatorios.setText("* Campos obrigatórios a serem preenchidos");

        jTableAgendamento.setModel(TMAgendamento);
        jTableAgendamento.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableAgendamentoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableAgendamento);

        jButtonAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Alterar.png"))); // NOI18N
        jButtonAlterar.setMnemonic('A');
        jButtonAlterar.setText("Alterar");
        jButtonAlterar.setToolTipText("Alterar");
        jButtonAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarActionPerformed(evt);
            }
        });

        jButtonIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Incluir.png"))); // NOI18N
        jButtonIncluir.setMnemonic('I');
        jButtonIncluir.setText("Incluir");
        jButtonIncluir.setToolTipText("Incluir");
        jButtonIncluir.setEnabled(false);
        jButtonIncluir.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                jButtonIncluirMouseDragged(evt);
            }
        });

        jButtonNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Novo.png"))); // NOI18N
        jButtonNovo.setMnemonic('m');
        jButtonNovo.setText("Novo");
        jButtonNovo.setEnabled(false);

        jComboBoxStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Atendido" }));

        jLabelStatus.setText("*Status:");

        jLabelAgendamento.setText("Agendamento:");

        jTextFieldAgendamento.setEnabled(false);

        jLabelPlanoSaude.setText("Plano de Saúde:");

        jLabelDenPlanoSaude.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N

        jCalendarAgendamento.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jCalendarAgendamentoPropertyChange(evt);
            }
        });

        javax.swing.GroupLayout jPanelAgendamentoMedicoLayout = new javax.swing.GroupLayout(jPanelAgendamentoMedico);
        jPanelAgendamentoMedico.setLayout(jPanelAgendamentoMedicoLayout);
        jPanelAgendamentoMedicoLayout.setHorizontalGroup(
            jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelAgendamentoMedicoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCalendarAgendamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelAgendamentoMedicoLayout.createSequentialGroup()
                        .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabelPlanoSaude)
                            .addComponent(jLabelAgendamento)
                            .addComponent(jLabelStatus))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBoxStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldAgendamento, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelDenPlanoSaude, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 523, Short.MAX_VALUE))
                    .addGroup(jPanelAgendamentoMedicoLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabelCamposObrigatorios)))
                .addContainerGap())
            .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanelAgendamentoMedicoLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1236, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        jPanelAgendamentoMedicoLayout.setVerticalGroup(
            jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelAgendamentoMedicoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabelCamposObrigatorios)
                        .addGroup(jPanelAgendamentoMedicoLayout.createSequentialGroup()
                            .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextFieldAgendamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabelAgendamento))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabelDenPlanoSaude, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabelPlanoSaude, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jComboBoxStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabelStatus))
                            .addGap(81, 81, 81)
                            .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButtonIncluir)
                                .addComponent(jButtonAlterar)
                                .addComponent(jButtonNovo))
                            .addGap(8, 8, 8)))
                    .addComponent(jCalendarAgendamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(322, Short.MAX_VALUE))
            .addGroup(jPanelAgendamentoMedicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanelAgendamentoMedicoLayout.createSequentialGroup()
                    .addGap(229, 229, 229)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)))
        );

        jTabbedPaneAgendamentoMedico.addTab("Agendamento", jPanelAgendamentoMedico);

        jLabelNomPaciente.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
        jLabelNomPaciente.setText("jLabel1");

        jLabelCodPaciente.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
        jLabelCodPaciente.setText("jLabel1");

        jTextAreaProntuario.setColumns(20);
        jTextAreaProntuario.setRows(5);
        jTextAreaProntuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextAreaProntuarioKeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(jTextAreaProntuario);

        jTableHistoricoProntuario.setModel(TMProntuario);
        jScrollPane4.setViewportView(jTableHistoricoProntuario);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Finalizar.png"))); // NOI18N
        jButton1.setMnemonic('i');
        jButton1.setText("Finalizar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabelPlanoSaudeProntuario.setText("Plano de Saúde:");

        jLabelDenPlanoSaudeProntuario.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
        jLabelDenPlanoSaudeProntuario.setText("jLabel1");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 641, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabelNomPaciente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelCodPaciente)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabelPlanoSaudeProntuario)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabelDenPlanoSaudeProntuario, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNomPaciente)
                    .addComponent(jLabelCodPaciente)
                    .addComponent(jLabelPlanoSaudeProntuario, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelDenPlanoSaudeProntuario, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)))
        );

        jTabbedPaneAgendamentoMedico.addTab("Prontuário", jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPaneAgendamentoMedico, javax.swing.GroupLayout.PREFERRED_SIZE, 1244, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPaneAgendamentoMedico)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTableAgendamentoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableAgendamentoMouseClicked
        String status = jTableAgendamento.getModel().getValueAt(jTableAgendamento.getSelectedRow(), 3).toString().trim();
        if (jTableAgendamento.getSelectedRow() != -1 && status.equals("Atendido")) {
            carregardados();

        } else {
            carregardados();
        }

        if (evt.getClickCount() == 2) {
            //if (jTableAgendamento.getSelectedRow() != -1 && !"Atendido".equals(status)) {            
            jTabbedPaneAgendamentoMedico.setEnabledAt(1, true);
            jTabbedPaneAgendamentoMedico.setEnabledAt(0, false);
            carregardadosprontuario();
            jTabbedPaneAgendamentoMedico.setSelectedIndex(1); //Trocar de aba automaticamente
            jTextAreaProntuario.grabFocus();
            try {
                cadastro();
                listaprontuario();
            } catch (SQLException ex) {
                Logger.getLogger(Jp_CadastroAgendamentoMedico.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                Logger.getLogger(Jp_CadastroAgendamentoMedico.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                listaprontuariomaxcodprontuario();
            } catch (SQLException ex) {
                Logger.getLogger(Jp_CadastroAgendamentoMedico.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                Logger.getLogger(Jp_CadastroAgendamentoMedico.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jTableAgendamentoMouseClicked

    private void jButtonIncluirMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonIncluirMouseDragged
        //        jButtonIncluir.setLocation(jButtonIncluir.getX() + evt.getX(), jButtonIncluir.getY() + evt.getY());
    }//GEN-LAST:event_jButtonIncluirMouseDragged

    private void jButtonAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarActionPerformed
        if (jTextFieldAgendamento.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Selecione um agendamento para ser alterado!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jTableAgendamento.grabFocus();
        } else {
            altera();
        }
    }//GEN-LAST:event_jButtonAlterarActionPerformed

    private void jTextAreaProntuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaProntuarioKeyReleased
        alteraProntuario();
    }//GEN-LAST:event_jTextAreaProntuarioKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int i = JOptionPane.showOptionDialog(this, "Deseja finalizar o prontuário?", "confirmação", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, btSimNao, btSimNao[1]);

        if (i == JOptionPane.YES_OPTION) {
            tabela = (DefaultTableModel) jTableHistoricoProntuario.getModel();
            tabela.setNumRows(0);  // zerar jTable
            jTextAreaProntuario.setText(null);
            jTabbedPaneAgendamentoMedico.setEnabledAt(1, false);
            jTabbedPaneAgendamentoMedico.setEnabledAt(0, true);
            jTabbedPaneAgendamentoMedico.setSelectedIndex(0); //Trocar de aba automaticamente
            remove();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jCalendarAgendamentoPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jCalendarAgendamentoPropertyChange
        try {
            listaagendamento();
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jCalendarAgendamentoPropertyChange
    public void listaagendamento() throws SQLException, ParseException {
        CRUDAgendamento CRUDAgend = new CRUDAgendamento();
        String data = new SimpleDateFormat("yyyy-MM-dd").format(jCalendarAgendamento.getDate());
        ListaAgendamento = CRUDAgend.getListaAgendamento(data);
        mostraAgendamento(ListaAgendamento);
    }

    public void listaprontuario() throws SQLException, ParseException {
        CRUDProntuario CRUDPront = new CRUDProntuario();
        ListaProntuario = CRUDPront.getListaProntuario(jLabelCodPaciente.getText().trim());
        mostraProntuario(ListaProntuario);
    }

    public void listaprontuariomaxcodprontuario() throws SQLException, ParseException {
        CRUDProntuario CRUDPront = new CRUDProntuario();
        ListaProntuario = CRUDPront.getListaProntuarioMaxCodProntuario(jLabelCodPaciente.getText().trim());
        mostraProntuarioMaxCodProntuario(ListaProntuario);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonAlterar;
    private javax.swing.JButton jButtonIncluir;
    private javax.swing.JButton jButtonNovo;
    private com.toedter.calendar.JCalendar jCalendarAgendamento;
    private javax.swing.JComboBox jComboBoxStatus;
    private javax.swing.JLabel jLabelAgendamento;
    private javax.swing.JLabel jLabelCamposObrigatorios;
    private javax.swing.JLabel jLabelCodPaciente;
    private javax.swing.JLabel jLabelDenPlanoSaude;
    private javax.swing.JLabel jLabelDenPlanoSaudeProntuario;
    private javax.swing.JLabel jLabelNomPaciente;
    private javax.swing.JLabel jLabelPlanoSaude;
    private javax.swing.JLabel jLabelPlanoSaudeProntuario;
    private javax.swing.JLabel jLabelStatus;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelAgendamentoMedico;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPaneAgendamentoMedico;
    private javax.swing.JTable jTableAgendamento;
    private javax.swing.JTable jTableHistoricoProntuario;
    private javax.swing.JTextArea jTextAreaProntuario;
    private javax.swing.JTextField jTextFieldAgendamento;
    // End of variables declaration//GEN-END:variables

    public void limpardados() {
        try {
            jTextFieldAgendamento.setText(null);
            jLabelDenPlanoSaude.setText(null);
        } catch (Exception ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void carregardados() {
        jTextFieldAgendamento.setText(ListaAgendamento.get(jTableAgendamento.getSelectedRow()).getCod_agendamento().toString());
        jLabelDenPlanoSaude.setText(ListaAgendamento.get(jTableAgendamento.getSelectedRow()).getDen_plano_saude());
    }

    public void carregardadosprontuario() {
        jLabelCodPaciente.setText(ListaAgendamento.get(jTableAgendamento.getSelectedRow()).getCod_paciente());
        jLabelNomPaciente.setText(ListaAgendamento.get(jTableAgendamento.getSelectedRow()).getPaciente());
        jLabelDenPlanoSaudeProntuario.setText(ListaAgendamento.get(jTableAgendamento.getSelectedRow()).getDen_plano_saude());
    }

    private void AlinhaColunaJTable() {
        int col = 0;
        jTableAgendamento.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); //barra horizontal na JTable 
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(100);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(110);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(60);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(45);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(230);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(230);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(120);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(80);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(80);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(80);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(130);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(230);
        jTableAgendamento.getColumnModel().getColumn(col++).setPreferredWidth(350);

        int colprontuario = 0;
        jTableHistoricoProntuario.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); //barra horizontal na JTable         
        jTableHistoricoProntuario.getColumnModel().getColumn(colprontuario++).setPreferredWidth(72);
        jTableHistoricoProntuario.getColumnModel().getColumn(colprontuario++).setPreferredWidth(560);
    }

    private void cadastro() {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
            BeanProntuario BP = new BeanProntuario();

            //BP.setCod_prontuario(1);            
            BP.setDen_prontuario(jTextAreaProntuario.getText());
            BP.setCod_pessoa(jLabelCodPaciente.getText());

            try {
                BP.setDt_prontuario(formatter.parse(data_atual.replace("/", ".")));
            } catch (ParseException ex) {
                Logger.getLogger(Jp_CadastroPessoa.class.getName()).log(Level.SEVERE, null, ex);
            }

            CRUDProntuario dao = new CRUDProntuario();
            dao.adiciona(BP);
            limpardados();
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void altera() {
        BeanAgendamento BA = new BeanAgendamento();
        BA.setCod_agendamento(Integer.valueOf(jTextFieldAgendamento.getText()));
        if (jComboBoxStatus.getSelectedItem().toString().equals("Em Aberto")) {
            BA.setStatus_agendamento("Em Aberto");
        }
        if (jComboBoxStatus.getSelectedItem().toString().equals("Em Atendimento")) {
            BA.setStatus_agendamento("Em Atendimento");
        }
        if (jComboBoxStatus.getSelectedItem().toString().equals("Atendido")) {
            BA.setStatus_agendamento("Atendido");
        }
        if (jComboBoxStatus.getSelectedItem().toString().equals("Cancelado")) {
            BA.setStatus_agendamento("Cancelado");
        }

        CRUDAgendamento dao = null;

        try {
            dao = new CRUDAgendamento();
            limpardados();
            try {
                listaagendamento();
            } catch (ParseException ex) {
                Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            dao.alteraMedico(BA);
            limpardados();
            try {
                listaagendamento();
            } catch (ParseException ex) {
                Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void alteraProntuario() {
        BeanProntuario BP = new BeanProntuario();
        BP.setCod_prontuario(cod_prontuario);
        BP.setDen_prontuario(jTextAreaProntuario.getText());

        CRUDProntuario dao = null;

        try {
            dao = new CRUDProntuario();
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            dao.altera(BP);
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            listaprontuario();
            JTableScroll.last(jTableHistoricoProntuario);
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoMedico.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoMedico.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void remove() {
        BeanProntuario BP = new BeanProntuario();
        CRUDProntuario dao = null;
        try {
            dao = new CRUDProntuario();
            dao.remove(BP);
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroAgendamentoMedico.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void mostraAgendamento(List<BeanAgendamento> ListaAgendamento) {
        if (TMAgendamento == null) {
            JOptionPane.showMessageDialog(null, "teste");
        } else {
            while (TMAgendamento.getRowCount() > 0) {
                TMAgendamento.removeRow(0);
            }
            if (ListaAgendamento.size() < 1) {
                //JOptionPane.showMessageDialog(null, "teste2");
            } else {
                String[] linha = new String[]{null, null};
                for (int i = 0; i < ListaAgendamento.size(); i++) {
                    TMAgendamento.addRow(linha);
                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getCod_agendamento(), i, 0);

                    String dt_agendamento = ListaAgendamento.get(i).getDt_agendamento().toString();
                    String str_dt_agendamento = dt_agendamento;
                    String[] array_dt_agendamento = str_dt_agendamento.split("-");
                    String dt_agendamento_alter = array_dt_agendamento[2] + "/" + array_dt_agendamento[1] + "/" + array_dt_agendamento[0];
                    TMAgendamento.setValueAt(dt_agendamento_alter, i, 1);

                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getHora_agendamento(), i, 2);
                    //jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("D:\\programacao\\JavaApplication2\\src\\Imagens\\Incluir.png")));
                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getStatus_agendamento().trim(), i, 3);

                    //jTableAgendamento.setForeground(Color.yellow);


                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getMedico(), i, 4);
                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getPaciente(), i, 5);
                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getTelefone(), i, 6);

                    String dt_nasc = ListaAgendamento.get(i).getDt_nasc().toString();
                    String str_dt_nasc = dt_nasc;
                    String[] array_dt_nasc = str_dt_nasc.split("-");
                    String dt_nasc_alter = array_dt_nasc[2] + "/" + array_dt_nasc[1] + "/" + array_dt_nasc[0];
                    TMAgendamento.setValueAt(dt_nasc_alter, i, 7);

                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getIdade(), i, 8);

                    if ("M".equals(ListaAgendamento.get(i).getSexo())) {
                        TMAgendamento.setValueAt("Masculino", i, 9);
                    } else {
                        TMAgendamento.setValueAt("Feminino", i, 9);
                    }

                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getCidade(), i, 10);
                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getEndereco().trim(), i, 11);
                    TMAgendamento.setValueAt(ListaAgendamento.get(i).getObservacao(), i, 12);

                    jTableAgendamento.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
                        public Component getTableCellRendererComponent(JTable table, Object value,
                                boolean isSelected, boolean hasFocus, int row, int column) {
                            super.getTableCellRendererComponent(table, value, isSelected,
                                    hasFocus, row, column);
                            Object coluna = table.getValueAt(row, 3);

                            if (column == 3 && coluna.equals("Atendido")) {
                                setBackground(Color.green);
                                setForeground(Color.green);
                            } else {
                                if (column == 3 && coluna.equals("Cancelado")) {
                                    setBackground(Color.red);
                                    setForeground(Color.red);
                                } else {
                                    if (column == 3 && coluna.equals("Em Aberto")) {
                                        setBackground(Color.yellow);
                                        setForeground(Color.yellow);
                                    } else {
                                        if (column == 3 && coluna.equals("Em Atendimento")) {
                                            setBackground(Color.blue);
                                            setForeground(Color.blue);
                                        } else {
                                            setForeground(Color.black);
                                            setBackground(null);
                                        }
                                    }
                                }
                            }
                            return this;
                        }
                    });
                }
            }
        }
    }

    private void mostraProntuario(List<BeanProntuario> ListaProntuario) {
        if (TMProntuario == null) {
            JOptionPane.showMessageDialog(null, "teste");
        } else {
            while (TMProntuario.getRowCount() > 0) {
                TMProntuario.removeRow(0);
            }
            if (ListaProntuario.size() < 1) {
                //JOptionPane.showMessageDialog(null, "teste2");
            } else {
                String[] linha = new String[]{null, null};
                for (int i = 0; i < ListaProntuario.size(); i++) {
                    TMProntuario.addRow(linha);

                    String dt_prontuario = ListaProntuario.get(i).getDt_prontuario().toString();
                    String str_dt_prontuario = dt_prontuario;
                    String[] array_dt_prontuario = str_dt_prontuario.split("-");
                    String dt_prontuario_alter = array_dt_prontuario[2] + "/" + array_dt_prontuario[1] + "/" + array_dt_prontuario[0];
                    TMProntuario.setValueAt(dt_prontuario_alter, i, 0);

                    String textocompleto = ListaProntuario.get(i).getDen_prontuario();
                    if (textocompleto.length() > 100) {
                        StringBuilder str = new StringBuilder();

                        //TMProntuario.setValueAt(ListaProntuario.get(i).getDen_prontuario(), i, 1);


                        str.append("<html>");
                        String textoparte1 = textocompleto.substring(0, 95);
                        TMProntuario.setValueAt(str.append(textoparte1), i, 1);
                        str.append("<br>");
                        String textoparte2 = textocompleto.substring(95, textocompleto.length());
                        TMProntuario.setValueAt(str.append(textoparte2), i, 1);
                        str.append("<br>");
                        str.append("<br>");
                        str.append("<br>");
                        str.append("<br>");


                        /*
                         String textoparte3 = textocompleto.substring(190, 285);
                         TMProntuario.setValueAt(str.append(textoparte3), i, 1);
                         str.append("<br>");
                         String textoparte4 = textocompleto.substring(285, 380);
                         TMProntuario.setValueAt(str.append(textoparte4), i, 1);
                         str.append("<br>");
                         String textoparte5 = textocompleto.substring(380, 475);
                         TMProntuario.setValueAt(str.append(textoparte5), i, 1);
                         str.append("<br>");
                         String textoparte6 = textocompleto.substring(475, 570);
                         TMProntuario.setValueAt(str.append(textoparte6), i, 1);
                         str.append("<br>");
                         String textoparte7 = textocompleto.substring(570, 665);
                         TMProntuario.setValueAt(str.append(textoparte7), i, 1); 
                         str.append("<br>");
                         String textoparte8 = textocompleto.substring(665, 760);
                         TMProntuario.setValueAt(str.append(textoparte8), i, 1); 
                         str.append("<br>");
                         String textoparte9 = textocompleto.substring(760, textocompleto.length());
                         TMProntuario.setValueAt(str.append(textoparte9), i, 1);
                         str.append("<br>");
                         */

                        str.append("</html>");
                        str.toString();

                        //http://www.guj.com.br/java/73120-tem-como-quebrar-linha-na-jtable

                    } else {
                        TMProntuario.setValueAt(textocompleto, i, 1);
                    }
                }
            }
        }
    }

    private void mostraProntuarioMaxCodProntuario(List<BeanProntuario> ListaProntuario) {
        for (int i = 0; i < ListaProntuario.size(); i++) {
            cod_prontuario = ListaProntuario.get(i).getCod_prontuario();
        }
    }
    
    public void run() {

        int delay = 5000;   // delay de 5 seg.
        int interval = 1000;  // intervalo de 1 seg.
        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                try {
                    listaagendamento();
                } catch (SQLException ex) {
                    Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                    Logger.getLogger(Jp_CadastroAgendamentoSecretaria.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }, delay, interval);
    }
}